package com.slowfly.rule.engine.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.slowfly.rule.engine.entity.Record;
import com.slowfly.rule.engine.entity.Scene;
import com.slowfly.rule.engine.mapper.RecordMapper;
import com.slowfly.rule.engine.param.RecordParam;
import com.slowfly.rule.engine.result.ExecuteRiskResult;
import com.slowfly.rule.engine.result.PageResult;
import com.slowfly.rule.engine.result.RecordResult;
import com.slowfly.rule.engine.service.IRecordService;
import com.slowfly.rule.engine.util.JsonUtils;
import com.slowfly.rule.engine.util.PageResultConvert;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author shalongfei
 * @since 2024-02-28
 */
@Service
public class RecordServiceImpl extends ServiceImpl<RecordMapper, Record> implements IRecordService {

    private static final ExecutorService executorService = Executors.newFixedThreadPool(4);

    public void save(long riskId, long start, Object riskParam, Scene scene, ExecuteRiskResult result) {
        Record record = new Record();
        record.setRiskId(riskId);
        record.setRiskParam(JsonUtils.toJson(riskParam));
        record.setSceneId(scene.getId());
        record.setSceneCode(scene.getCode());
        record.setSceneName(scene.getName());
        record.setResultType(result.getResultType());
        record.setResultMsg(result.getResultMsg());
        record.setTemplateId(result.getTemplateId());
        record.setNoticeMsg(result.getNoticeMsg());
        if (CollectionUtils.isNotEmpty(result.getNoticeUsers())) {
            record.setNoticeUsers(JsonUtils.toJson(result.getNoticeUsers()));
        }
        record.setCost(System.currentTimeMillis() - start);
        CompletableFuture.runAsync(() -> {
            // 保存日志
            save(record);
        }, executorService);
    }

    public PageResult<RecordResult> pageRecord(RecordParam param) {
        LambdaQueryWrapper<Record> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Objects.nonNull(param.getSceneId()), Record::getSceneId, param.getSceneId());
        queryWrapper.eq(Objects.nonNull(param.getRiskId()), Record::getRiskId, param.getRiskId());
        queryWrapper.eq(Objects.nonNull(param.getResultType()), Record::getResultType, param.getResultType());
        queryWrapper.orderByDesc(Record::getCreateTime);
        Page<Record> page = page(new Page<>(param.getPageNo(), param.getPageSize()), queryWrapper);
        return PageResultConvert.convert(page, RecordResult.class);
    }
}
